package com.ruoyi.basebill.service.impl;

import com.ruoyi.basebill.domain.*;
import com.ruoyi.basebill.service.IPushSaleReturnService;
import com.ruoyi.basebill.service.common.AbstractPushSaleReturn;
import com.ruoyi.basebill.service.exception.DataNullException;
import com.ruoyi.basebill.task.util.OmsTaskUtil;
import com.ruoyi.basebill.util.OmsUtil;
import com.ruoyi.basedata.domain.BdCustomer;
import com.ruoyi.basedata.domain.BdWarehouse;
import com.ruoyi.basedata.domain.OmsOrgunit;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @projectName: wfz
 * @package: com.ruoyi.basebill.service.impl
 * @className: PushSaleReturnServiceImpl
 * @author: Eric
 * @description: TODO
 * @date: 2023/2/20 15:43
 * @version: 1.0
 */
@Service
public class PushSaleReturnServiceImpl extends AbstractPushSaleReturn implements IPushSaleReturnService {

    @Autowired
    private OmsTaskUtil omsTaskUtil;

    @Autowired
    private OmsUtil omsUtil;

    private final static Logger logger = LoggerFactory.getLogger(PushSaleReturnServiceImpl.class);

    //外部组织的销售出库单
    @Override
    public OmsSaleissuebill pushSaleIssueForOut(OmsSalereturnbill omsSalereturnbill, StringBuffer reason, String orgUnitCode) throws DataNullException {
        OmsSaleissuebill omsSaleissuebill = super.pushSaleIssue(omsSalereturnbill);
        logger.info("外部下推表头实体:"+omsSalereturnbill.toString());

        String hasnote = omsSalereturnbill.getHasnote();
        String transactiontype = omsSalereturnbill.getTransactiontype();
        omsSaleissuebill.setBillnumber(omsSalereturnbill.getCode());
        omsSaleissuebill.setStorageorgnumber(omsSalereturnbill.getInvoicecode());
        omsSaleissuebill.setStorageorgname(omsSalereturnbill.getInvoicename());
        omsSaleissuebill.setBiztypenumber("211");
        omsSaleissuebill.setBiztypename("普通销售退货");
        omsSaleissuebill.setTransactiontypenumber(transactiontype);
//        omsSaleissuebill.setTransactiontypename("标准销售退货");
        omsSaleissuebill.setCustomernumber(omsSalereturnbill.getCustomercode());
        omsSaleissuebill.setCustomername(omsSalereturnbill.getCustomername());
        omsSaleissuebill.setAccountcompanyname(omsSalereturnbill.getInvoicename());
        omsSaleissuebill.setAccountcompanynumber(omsSalereturnbill.getInvoicecode());
        omsSaleissuebill.setCostcentername(omsSalereturnbill.getSalescostcentername());
        omsSaleissuebill.setCostcenternumber(omsSalereturnbill.getSalescostcentercode());
        omsSaleissuebill.setIsoutcustomer(1l);
        omsSaleissuebill.setDescription(hasnote);
        List<OmsSaleissuebillentry> omsSaleissuebillentryList = omsSaleissuebill.getOmsSaleissuebillentryList();
        List<OmsSalereturnbillentry> omsSalereturnbillentryList = omsSalereturnbill.getOmsSalereturnbillentryList();

        Map<String, String> map = omsUtil.judOutWareHouse(omsSalereturnbill, omsSalereturnbill.getOmsSalereturnbillentryList().get(0));
        if(StringUtils.isEmpty(map)){
            reason.append("未找到客户"+omsSalereturnbill.getCustomercode()+"的分公司门店仓");
            throw new DataNullException(reason.toString());

        }
        String warehouseCode = map.get("code");
        String warehouseName = map.get("name");
        for (int i = 0; i < omsSaleissuebillentryList.size(); i++) {
            OmsSaleissuebillentry omsSaleissuebillentry = omsSaleissuebillentryList.get(i);
            OmsSalereturnbillentry omsSalereturnbillentry = omsSalereturnbillentryList.get(i);

            logger.info("外部下推分录实体:"+omsSalereturnbillentry.toString());
            omsSaleissuebillentry.setWarehousename(warehouseName);
            omsSaleissuebillentry.setWarehousenumber(warehouseCode);
            BigDecimal qty = omsSalereturnbillentry.getQty();

//            BigDecimal qualityundertakeqty = omsSalereturnbillentry.getQualityundertakeqty();
            BigDecimal qualityrefuseqty = omsSalereturnbillentry.getQualityrefuseqty();
            BigDecimal warehouserefuseqty = omsSalereturnbillentry.getWarehouserefuseqty();
            qty = qty.subtract(qualityrefuseqty).subtract(warehouserefuseqty).negate().setScale(4,4);

            omsSaleissuebillentry.setQty(qty.setScale(4,BigDecimal.ROUND_HALF_UP));

            BigDecimal notaxprice = omsSalereturnbillentry.getNotaxprice();
            BigDecimal taxrate = omsSalereturnbillentry.getTaxrate();
            //系统含税单价
            BigDecimal systaxprice = omsSalereturnbillentry.getSystaxprice();
            BigDecimal taxprice = omsSalereturnbillentry.getTaxprice();
            BigDecimal taxamount = omsSalereturnbillentry.getTaxamount().negate();//含税金额
            BigDecimal notaxamount = omsSalereturnbillentry.getNotaxamount().negate(); //不含税金额
            BigDecimal tax = omsSalereturnbillentry.getTax().negate();
            logger.info("外部下推单价:"+notaxprice);
//            logger.info("外部下推数量:"+qty);
            BigDecimal amount = notaxprice.multiply(qty).setScale(2,4);

            BigDecimal taxamountf = taxprice.multiply(qty).setScale(2,4);
            BigDecimal taxf = taxamountf.subtract(amount);
            omsSaleissuebillentry.setPrice(notaxprice);
            omsSaleissuebillentry.setTaxrate(taxrate);
            //系统含税单价
            omsSaleissuebillentry.setSystaxprice(systaxprice);
            omsSaleissuebillentry.setTaxprice(taxprice);
            omsSaleissuebillentry.setAmount(amount);
            omsSaleissuebillentry.setBaseqty(qty);
            omsSaleissuebillentry.setTax(taxf);
            omsSaleissuebillentry.setCustomerOrderNo(omsSalereturnbillentry.getCustomerorder());

            omsSaleissuebillentry.setTaxamount(taxamountf);
            //对外销出单单独设置是否赠品
            omsSaleissuebillentry.setIspresent(omsSalereturnbillentry.getIsgift());
            //设置备注
            omsSaleissuebillentry.setRemark(omsSalereturnbillentry.getRemark());

        }
        return omsSaleissuebill;
    }

    /**
     * 上级组织的销售出库
     * @param omsSalereturnbill
     * @param reason
     * @param orgUnitCode 本级组织
     * @param supOrg 上级组织
     * @return
     */
    @Override
    public OmsSaleissuebill pushSaleIssueForSup(OmsSalereturnbill omsSalereturnbill, StringBuffer reason, String orgUnitCode,String supOrg)throws DataNullException {
        OmsSaleissuebill omsSaleissuebill = super.pushSaleIssue(omsSalereturnbill);
         //根据上级组织
        OmsOrgunit omsOrgunit = omsUtil.getOmsOrgunit(supOrg);

        BdCustomer customer = omsUtil.getCustomerByOrg(orgUnitCode);
        String orgnumber = omsOrgunit.getOrgnumber();
        String orgname = omsOrgunit.getOrgname();
        String customername = customer.getCustomername();
        String customernumber = customer.getCustomernumber();

        String s = omsTaskUtil.setBillNumber(omsSaleissuebill);
        omsSaleissuebill.setBillnumber(s);
        omsSaleissuebill.setStorageorgname(orgname);
        omsSaleissuebill.setStorageorgnumber(orgnumber);
        omsSaleissuebill.setBiztypenumber("211");
        omsSaleissuebill.setBiztypename("普通销售退货");
        omsSaleissuebill.setTransactiontypenumber("013");
        omsSaleissuebill.setTransactiontypename("成本出库退货");
        omsSaleissuebill.setCustomername(customername);
        omsSaleissuebill.setCustomernumber(customernumber);
        omsSaleissuebill.setAccountcompanynumber(orgnumber);
        omsSaleissuebill.setAccountcompanyname(orgname);
        omsSaleissuebill.setCostcentername("关联单位");
        omsSaleissuebill.setCostcenternumber("1.91");
        omsSaleissuebill.setIsoutcustomer(0l);

        Date tradecreatedat = omsSalereturnbill.getCloseat();

        List<OmsSaleissuebillentry> omsSaleissuebillentryList = omsSaleissuebill.getOmsSaleissuebillentryList();
        List<OmsSalereturnbillentry> omsSalereturnbillentryList = omsSalereturnbill.getOmsSalereturnbillentryList();

        Map<String, String> wareHouseForSal = omsUtil.getWareHouseForSal(omsSalereturnbillentryList.get(0), supOrg);
        for (int i = 0; i <omsSaleissuebillentryList.size() ; i++) {
            OmsSalereturnbillentry omsSalereturnbillentry = omsSalereturnbillentryList.get(i);
            OmsSaleissuebillentry omsSaleissuebillentry = omsSaleissuebillentryList.get(i);
            String materialnumber = omsSaleissuebillentry.getMaterialnumber();
            if (wareHouseForSal!=null){
                String wareHoseNum = wareHouseForSal.get("code");
                String name = wareHouseForSal.get("name");
                omsSaleissuebillentry.setWarehousenumber(wareHoseNum);
                omsSaleissuebillentry.setWarehousename(name);
            }else{
                throw new DataNullException("未找到"+supOrg+"的中转仓");
            }
            BigDecimal qty = omsSalereturnbillentry.getQty();
            BigDecimal qualityrefuseqty = omsSalereturnbillentry.getQualityrefuseqty();
            BigDecimal warehouserefuseqty = omsSalereturnbillentry.getWarehouserefuseqty();
            qty = qty.subtract(qualityrefuseqty).subtract(warehouserefuseqty).negate().setScale(4,4);
            omsSaleissuebillentry.setQty(qty);
            omsSaleissuebillentry.setBaseqty(qty);
            //系统含税单价
            BigDecimal systaxprice = omsSalereturnbillentry.getSystaxprice();
            omsSaleissuebillentry.setSystaxprice(systaxprice);

            BigDecimal taxRate = omsSalereturnbillentry.getTaxrate();
            StringBuffer buffer = new StringBuffer();
            BigDecimal taxPrice = omsTaskUtil.getTaxPrice(omsOrgunit, customernumber, tradecreatedat, materialnumber, buffer);
            BigDecimal tempTaxRate = OmsTaskUtil.formatTaxRate(taxRate);

            if (taxPrice!=null){//含税单价
                //单价 = 含税单价/(1+税率)
                BigDecimal price = taxPrice.divide(tempTaxRate.add(BigDecimal.ONE), 6, 4);
                //价税合计 = 含税单价*数量
                BigDecimal taxAmount = taxPrice.multiply(qty).setScale(6, RoundingMode.HALF_UP);
                //金额 = 价税合计/（1+税率）
//                BigDecimal amount = taxAmount.divide(tempTaxRate.add(BigDecimal.ONE), 2, 4);
                BigDecimal amount = price.multiply(qty).setScale(2, RoundingMode.HALF_UP);
                //税额
                BigDecimal tax = taxAmount.subtract(amount);

                omsSaleissuebillentry.setPrice(price);
                omsSaleissuebillentry.setTaxprice(taxPrice);
                omsSaleissuebillentry.setAmount(amount);
                omsSaleissuebillentry.setTax(tax);
                omsSaleissuebillentry.setTaxrate(taxRate);
                omsSaleissuebillentry.setTaxamount(taxAmount);
            }else{
                throw new DataNullException(buffer.toString());
            }

        }


        return omsSaleissuebill;
    }

    /**
     * 果不等，则生成发货组织的销售出库单（红字）和一级组织的采购入库单（红字）
     * @param omsSalereturnbill
     * @param reason 理由
     * @param orgUnitCode 一级组织
     * @param Org 发货组织
     * @return
     */
    @Override
    public OmsSaleissuebill pushSaleIssueForFir(OmsSalereturnbill omsSalereturnbill, StringBuffer reason, String orgUnitCode,String Org) throws DataNullException{
        OmsSaleissuebill omsSaleissuebill = super.pushSaleIssue(omsSalereturnbill);
        OmsOrgunit omsOrgunit = omsUtil.getOmsOrgunit(Org);

        BdCustomer customer = omsUtil.getCustomerByOrg(orgUnitCode); //一级组织
        String orgnumber = omsOrgunit.getOrgnumber();
        String orgname = omsOrgunit.getOrgname();
        String customername = customer.getCustomername();
        String customernumber = customer.getCustomernumber();

        String s = omsTaskUtil.setBillNumber(omsSaleissuebill);
        omsSaleissuebill.setBillnumber(s);
        omsSaleissuebill.setStorageorgname(orgname);
        omsSaleissuebill.setStorageorgnumber(orgnumber);
        omsSaleissuebill.setBiztypenumber("211");
        omsSaleissuebill.setBiztypename("普通销售退货");
        omsSaleissuebill.setTransactiontypenumber("013");
        omsSaleissuebill.setTransactiontypename("成本出库退货");
        omsSaleissuebill.setAccountcompanyname(orgname);
        omsSaleissuebill.setAccountcompanynumber(orgnumber);
        omsSaleissuebill.setCustomername(customername);
        omsSaleissuebill.setCustomernumber(customernumber);
        omsSaleissuebill.setCostcenternumber("1.91");
        omsSaleissuebill.setCostcentername("关联单位");
        omsSaleissuebill.setIsoutcustomer(0l);

        Date tradecreatedat = omsSalereturnbill.getCloseat();

        List<OmsSaleissuebillentry> omsSaleissuebillentryList = omsSaleissuebill.getOmsSaleissuebillentryList();
        List<OmsSalereturnbillentry> omsSalereturnbillentryList = omsSalereturnbill.getOmsSalereturnbillentryList();


        for (int i = 0; i <omsSaleissuebillentryList.size() ; i++) {
            OmsSalereturnbillentry omsSalereturnbillentry = omsSalereturnbillentryList.get(i);
            OmsSaleissuebillentry omsSaleissuebillentry = omsSaleissuebillentryList.get(i);
            String materialnumber = omsSaleissuebillentry.getMaterialnumber();
            String returnwarehousecode = omsSalereturnbillentry.getReturnwarehousecode();
            String returnwarehousename = omsSalereturnbillentry.getReturnwarehousename();
            omsSaleissuebillentry.setWarehousenumber(returnwarehousecode);
            omsSaleissuebillentry.setWarehousename(returnwarehousename);
            BigDecimal qty = omsSalereturnbillentry.getQty();
            BigDecimal qualityrefuseqty = omsSalereturnbillentry.getQualityrefuseqty();
            BigDecimal warehouserefuseqty = omsSalereturnbillentry.getWarehouserefuseqty();
            qty = qty.subtract(qualityrefuseqty).subtract(warehouserefuseqty).negate().setScale(4,4);
            omsSaleissuebillentry.setQty(qty);
            omsSaleissuebillentry.setBaseqty(qty);
            //系统含税单价
            BigDecimal systaxprice = omsSalereturnbillentry.getSystaxprice();
            omsSaleissuebillentry.setSystaxprice(systaxprice);

            BigDecimal taxRate = omsSalereturnbillentry.getTaxrate();
            StringBuffer buffer = new StringBuffer();
            BigDecimal taxPrice = omsTaskUtil.getTaxPrice(omsOrgunit, customernumber, tradecreatedat, materialnumber, buffer);
            BigDecimal tempTaxRate = OmsTaskUtil.formatTaxRate(taxRate);

            if (taxPrice!=null){//含税单价
                //单价 = 含税单价/(1+税率)
                BigDecimal price = taxPrice.divide(tempTaxRate.add(BigDecimal.ONE), 6, 4);
                //价税合计 = 含税单价*数量
                BigDecimal taxAmount = taxPrice.multiply(qty).setScale(6,RoundingMode.HALF_UP);
                //金额 = 价税合计/（1+税率）
//                BigDecimal amount = taxAmount.divide(tempTaxRate.add(BigDecimal.ONE), 2, 4);
                BigDecimal amount = price.multiply(qty).setScale(2,RoundingMode.HALF_UP);
                //税额
                BigDecimal tax = taxAmount.subtract(amount);

                omsSaleissuebillentry.setPrice(price);
                omsSaleissuebillentry.setTaxprice(taxPrice);
                omsSaleissuebillentry.setAmount(amount);
                omsSaleissuebillentry.setTax(tax);
                omsSaleissuebillentry.setTaxrate(taxRate);
                omsSaleissuebillentry.setTaxamount(taxAmount);
            }else{
                throw new DataNullException(buffer.toString());
            }

        }
        return omsSaleissuebill;
    }

    //一级组织的库存调拨单
    @Override
    public OmsStocktransferbill pushStockTransferForFir(OmsSalereturnbill omsSalereturnbill, StringBuffer reason)throws DataNullException {
        OmsStocktransferbill omsStocktransferbill = super.pushStockTransfer(omsSalereturnbill);
        String invoicecode = omsSalereturnbill.getInvoicecode();
        String invoicename = omsSalereturnbill.getInvoicename();
        String customercode = omsSalereturnbill.getCustomercode();
        omsStocktransferbill.setIssuestorageorgnumber(invoicecode);
        omsStocktransferbill.setIssuestorageorgname(invoicename);
        omsStocktransferbill.setReceiptstorageorgnumber(invoicecode);
        omsStocktransferbill.setReceiptstorageorgname(invoicename);
        omsStocktransferbill.setOutaccountcompanyname(invoicename);
        omsStocktransferbill.setOutaccountcompanynumber(invoicecode);
        omsStocktransferbill.setInaccountcompanynumber(invoicecode);
        omsStocktransferbill.setInaccountcompanyname(invoicename);
//        omsStocktransferbill.setOutcostcenternumber("1.91");
//        omsStocktransferbill.setOutcostcentername("关联单位");

        List<OmsStocktransferbillentry> omsStocktransferbillentryList = omsStocktransferbill.getOmsStocktransferbillentryList();
        List<OmsSalereturnbillentry> omsSalereturnbillentryList = omsSalereturnbill.getOmsSalereturnbillentryList();
        for (int i = 0; i < omsStocktransferbillentryList.size(); i++) {
            OmsSalereturnbillentry omsSalereturnbillentry = omsSalereturnbillentryList.get(i);
            OmsStocktransferbillentry omsStocktransferbillentry = omsStocktransferbillentryList.get(i);
            String exitwarehousecode = omsSalereturnbill.getExitwarehousecode();
            String exitwarehousename = omsSalereturnbill.getExitwarehousename();
            omsStocktransferbillentry.setIssuewarehousenumber(exitwarehousecode);
            omsStocktransferbillentry.setIssuewarehousename(exitwarehousename);
            Map<String, String> map = omsUtil.judReWareHouse(omsSalereturnbill, omsSalereturnbillentryList.get(0));
            if (StringUtils.isEmpty(map)){
                throw new DataNullException("未找到客户"+customercode+"的分公司门店仓；");
            }
            String code = map.get("code");
            String name = map.get("name");
            omsStocktransferbillentry.setReceiptwarehousename(name);
            omsStocktransferbillentry.setReceiptwarehousenumber(code);

            BigDecimal qty = omsSalereturnbillentry.getQty();
            BigDecimal qualityrefuseqty = omsSalereturnbillentry.getQualityrefuseqty();
            BigDecimal warehouserefuseqty = omsSalereturnbillentry.getWarehouserefuseqty();

            qty = qty.subtract(qualityrefuseqty).subtract(warehouserefuseqty).setScale(4,4);
            omsStocktransferbillentry.setQty(qty);
            omsStocktransferbillentry.setBaseqty(qty);
        }


        return omsStocktransferbill;
    }

    @Override
    public OmsStocktransferbill pushStockTransferForQty(OmsSalereturnbill omsSalereturnbill, StringBuffer reason) throws DataNullException{
        OmsStocktransferbill omsStocktransferbill = super.pushStockTransfer(omsSalereturnbill);
        List<OmsStocktransferbillentry> omsStocktransferbillentryList = omsStocktransferbill.getOmsStocktransferbillentryList();
        List<OmsSalereturnbillentry> omsSalereturnbillentryList = omsSalereturnbill.getOmsSalereturnbillentryList();
        String returnwarehousecode = omsSalereturnbillentryList.get(0).getReturnwarehousecode();
        BdWarehouse bdWarehouse = omsUtil.getBdWarehouse(returnwarehousecode);
        String storageorgname = bdWarehouse.getStorageorgname();
        String storageorgnumber = bdWarehouse.getStorageorgnumber();
        omsStocktransferbill.setIssuestorageorgname(storageorgname);
        omsStocktransferbill.setIssuestorageorgnumber(storageorgnumber);
        omsStocktransferbill.setReceiptstorageorgname(storageorgname);
        omsStocktransferbill.setReceiptstorageorgnumber(storageorgnumber);

        for (int i = 0; i < omsStocktransferbillentryList.size(); i++) {
            OmsStocktransferbillentry omsStocktransferbillentry = omsStocktransferbillentryList.get(i);
            OmsSalereturnbillentry omsSalereturnbillentry = omsSalereturnbillentryList.get(i);
            String warehousecode = omsSalereturnbillentry.getReturnwarehousecode();
            String returnwarehousename = omsSalereturnbillentry.getReturnwarehousename();
            BigDecimal warehousenoneqty = omsSalereturnbillentry.getWarehousenoneqty();

            String virtualreturnwarehousecode = omsSalereturnbillentry.getVirtualreturnwarehousecode();
            String virtualreturnwarehousename = omsSalereturnbillentry.getVirtualreturnwarehousename();

            omsStocktransferbillentry.setIssuewarehousenumber(warehousecode);
            omsStocktransferbillentry.setIssuewarehousename(returnwarehousename);
            omsStocktransferbillentry.setBaseqty(warehousenoneqty);
            omsStocktransferbillentry.setQty(warehousenoneqty);

            omsStocktransferbillentry.setReceiptwarehousename(virtualreturnwarehousename);
            omsStocktransferbillentry.setReceiptwarehousenumber(virtualreturnwarehousecode);

        }


        return omsStocktransferbill;
    }

    /**
     *
     * @param omsSalereturnbill 销售出库单
     * @param reason 理由
     * @param orgUnitCode  本级组织编码
     * @param orgSup  上级组织编码
     * @param isFirst 是否第一次
     * @return
     */
    @Override
    public OmsPurinwarehsbill pushPurInWarehseForlow(OmsSalereturnbill omsSalereturnbill, StringBuffer reason, String orgUnitCode,String orgSup,Boolean isFirst)throws DataNullException {
        OmsPurinwarehsbill omsPurinwarehsbill = super.pushPurInWarehs(omsSalereturnbill, orgUnitCode,orgSup,reason);

        OmsOrgunit omsOrgunit = omsUtil.getOmsOrgunit(orgUnitCode);
        OmsOrgunit orgSupUnit = omsUtil.getOmsOrgunit(orgSup);
        BdCustomer customerByOrg = omsUtil.getCustomerByOrg(orgUnitCode);
        String customercode = customerByOrg.getCustomernumber();
        Date tradecreatedat = omsSalereturnbill.getCloseat();

        List<OmsSalereturnbillentry> omsSalereturnbillentryList = omsSalereturnbill.getOmsSalereturnbillentryList();
        List<OmsPurinwarehsbillentry> omsPurinwarehsbillentryList = omsPurinwarehsbill.getOmsPurinwarehsbillentryList();
        for (int i =0;i<omsPurinwarehsbillentryList.size();i++){
            OmsPurinwarehsbillentry omsPurinwarehsbillentry = omsPurinwarehsbillentryList.get(i);
            String materialnumber = omsPurinwarehsbillentry.getMaterialnumber();
            OmsSalereturnbillentry omsSalereturnbillentry = omsSalereturnbillentryList.get(i);
            BigDecimal qty = omsSalereturnbillentry.getQty();
            BigDecimal qualityrefuseqty = omsSalereturnbillentry.getQualityrefuseqty();
            BigDecimal warehouserefuseqty = omsSalereturnbillentry.getWarehouserefuseqty();
            qty = qty.subtract(qualityrefuseqty).subtract(warehouserefuseqty).negate().setScale(4,4);
            BigDecimal taxRate = omsSalereturnbillentry.getTaxrate();
            StringBuffer buffer = new StringBuffer();
            BigDecimal taxPrice = omsTaskUtil.getTaxPrice(orgSupUnit, customercode, tradecreatedat, materialnumber, buffer); //客户传本级，组织传上级
            BigDecimal tempTaxRate = OmsTaskUtil.formatTaxRate(taxRate);
            Map<String, String> wareHouseForPur = omsUtil.getWareHouseForPur(omsSalereturnbill, omsSalereturnbillentry, isFirst, orgUnitCode);
            if (StringUtils.isEmpty(wareHouseForPur)){
                throw new DataNullException("仓库转换出错");
            }
            omsPurinwarehsbillentry.setWarehousenumber(wareHouseForPur.get("code"));
            omsPurinwarehsbillentry.setWarehousename(wareHouseForPur.get("name"));
            omsPurinwarehsbillentry.setQty(qty);
            omsPurinwarehsbillentry.setBaseqty(qty);


            if (taxPrice!=null){//含税单价
                //单价 = 含税单价/(1+税率)
                BigDecimal price = taxPrice.divide(tempTaxRate.add(BigDecimal.ONE), 6, 4);
                //价税合计 = 含税单价*数量
                BigDecimal taxAmount = taxPrice.multiply(qty).setScale(6,RoundingMode.HALF_UP);
                //金额 = 价税合计/（1+税率）
//                BigDecimal amount = taxAmount.divide(tempTaxRate.add(BigDecimal.ONE), 2, 4);
                BigDecimal amount = price.multiply(qty).setScale(2,RoundingMode.HALF_UP);
                //税额
                BigDecimal tax = taxAmount.subtract(amount);

                omsPurinwarehsbillentry.setPrice(price);
                omsPurinwarehsbillentry.setTaxprice(taxPrice);
                omsPurinwarehsbillentry.setAmount(amount);
                omsPurinwarehsbillentry.setTax(tax);
                omsPurinwarehsbillentry.setTaxrate(taxRate);
                omsPurinwarehsbillentry.setTaxamount(taxAmount);
            }else{
                throw new DataNullException(buffer.toString());
            }

        }
        return omsPurinwarehsbill;
    }

    /**
     *
     * @param omsSalereturnbill
     * @param reason
     * @param orgsup 发货组织，第一行分录的仓库的库存组织
     * @param orgUnitCode 一级组织名称
     * @return
     * @throws
     */
    @Override
    public OmsPurinwarehsbill pushPurInWarehseForFirst(OmsSalereturnbill omsSalereturnbill, StringBuffer reason,String orgsup,String orgUnitCode)throws DataNullException{
        OmsPurinwarehsbill omsPurinwarehsbill = super.pushPurInWarehs(omsSalereturnbill, orgUnitCode,orgsup,reason);

        OmsOrgunit omsOrgunit = omsUtil.getOmsOrgunit(orgUnitCode);
        BdCustomer customerByOrg = omsUtil.getCustomerByOrg(orgsup); //用于计算结算价格
        if(customerByOrg==null){
            throw new DataNullException("未找到组织"+orgsup+"的客户");
        }
        String customercode = omsSalereturnbill.getCustomercode();
        Date tradecreatedat = omsSalereturnbill.getCloseat();
        String salescostcentercode = omsSalereturnbill.getSalescostcentercode();
        String transferwhname = omsOrgunit.getTransferwhname();
        String transferwhnumber = omsOrgunit.getTransferwhnumber();

        if(StringUtils.isEmpty(transferwhnumber)){
            throw new DataNullException("未找到"+orgUnitCode+"的中转仓");
        }


        List<OmsSalereturnbillentry> omsSalereturnbillentryList = omsSalereturnbill.getOmsSalereturnbillentryList();
        List<OmsPurinwarehsbillentry> omsPurinwarehsbillentryList = omsPurinwarehsbill.getOmsPurinwarehsbillentryList();
        for (int i =0;i<omsPurinwarehsbillentryList.size();i++){
            OmsPurinwarehsbillentry omsPurinwarehsbillentry = omsPurinwarehsbillentryList.get(i);
            String materialnumber = omsPurinwarehsbillentry.getMaterialnumber();
            OmsSalereturnbillentry omsSalereturnbillentry = omsSalereturnbillentryList.get(i);
            BigDecimal qty = omsSalereturnbillentry.getQty();
            BigDecimal qualityrefuseqty = omsSalereturnbillentry.getQualityrefuseqty();
            BigDecimal warehouserefuseqty = omsSalereturnbillentry.getWarehouserefuseqty();
            qty = qty.subtract(qualityrefuseqty).subtract(warehouserefuseqty).negate().setScale(4,4);
            BigDecimal taxRate = omsSalereturnbillentry.getTaxrate();
            StringBuffer buffer = new StringBuffer();
            BigDecimal taxPrice = omsTaskUtil.getTaxPrice(omsOrgunit, customerByOrg.getCustomernumber(), tradecreatedat, materialnumber, buffer);
            BigDecimal tempTaxRate = OmsTaskUtil.formatTaxRate(taxRate);
            omsPurinwarehsbillentry.setWarehousenumber(transferwhnumber);
            omsPurinwarehsbillentry.setWarehousename(transferwhname);
            omsPurinwarehsbillentry.setQty(qty);
            omsPurinwarehsbillentry.setBaseqty(qty);

            if (taxPrice!=null){//含税单价
                //单价 = 含税单价/(1+税率)
                BigDecimal price = taxPrice.divide(tempTaxRate.add(BigDecimal.ONE), 6, 4);
                //价税合计 = 含税单价*数量
                BigDecimal taxAmount = taxPrice.multiply(qty).setScale(6,RoundingMode.HALF_UP);
                //金额 = 价税合计/（1+税率）
//                BigDecimal amount = taxAmount.divide(tempTaxRate.add(BigDecimal.ONE), 2, 4);
                BigDecimal amount = price.multiply(qty).setScale(2,RoundingMode.HALF_UP);
                //税额
                BigDecimal tax = taxAmount.subtract(amount);

                omsPurinwarehsbillentry.setPrice(price);
                omsPurinwarehsbillentry.setTaxprice(taxPrice);
                omsPurinwarehsbillentry.setAmount(amount);
                omsPurinwarehsbillentry.setTax(tax);
                omsPurinwarehsbillentry.setTaxrate(taxRate);
                omsPurinwarehsbillentry.setTaxamount(taxAmount);
            }else{
                throw new DataNullException(buffer.toString());
            }

        }
        return omsPurinwarehsbill;
    }

    @Override
    public OmsOtherissuebill pushOtherIssue(OmsSalereturnbill omsSalereturnbill, StringBuffer reason) throws DataNullException{
        OmsOtherissuebill omsOtherissuebill = new OmsOtherissuebill();
        //来源系统
        String srcsys = omsSalereturnbill.getSrcsys();
        String hasnote = omsSalereturnbill.getHasnote();//备注

        //发货组织，第一行明细的仓库的库存组织
        OmsSalereturnbillentry omsSalereturnbillentry = omsSalereturnbill.getOmsSalereturnbillentryList().get(0);
        String returnwarehousecode = omsSalereturnbillentry.getReturnwarehousecode(); //第一行明细仓库

        BdWarehouse bdWarehouse = omsUtil.getBdWarehouse(returnwarehousecode);

//        OmsOrgunit omsOrgunit = omsUtil.getOmsOrgunit(returnwarehousecode);
//        String transferwhnumber = omsOrgunit.getTransferwhnumber();
//        String transferwhname = omsOrgunit.getTransferwhname();

        String storageorgnumber = bdWarehouse.getStorageorgnumber();
        String storageorgname = bdWarehouse.getStorageorgname();

        Date tradecreatedat = omsSalereturnbill.getCloseat();
        omsOtherissuebill.setBizdate(tradecreatedat);
        String billNumber = omsTaskUtil.setBillNumber(omsOtherissuebill);
        omsOtherissuebill.setBillnumber(billNumber);


        omsOtherissuebill.setStorageorgnumber(storageorgnumber);
        omsOtherissuebill.setStorageorgname(storageorgname);
        omsOtherissuebill.setBiztypenumber("510");
        omsOtherissuebill.setBiztypename("普通出库");
        if ("zc".equals(srcsys)){
            //成本中心数据设置
            omsOtherissuebill.setCostcenternumber(omsSalereturnbill.getSalescostcentercode());
            omsOtherissuebill.setCostcentername(omsSalereturnbill.getSalescostcentername());
            //事务类型数据设置
            omsOtherissuebill.setTransactiontypenumber("0030");
            omsOtherissuebill.setTransactiontypename("报废出库(损毁及其他)");
        }else {
            //成本中心数据设置
            omsOtherissuebill.setCostcenternumber("1.10.100.27.08");
            omsOtherissuebill.setCostcentername("投诉管理部");
            //事务类型数据设置
            omsOtherissuebill.setTransactiontypenumber("006003");
            omsOtherissuebill.setTransactiontypename("投诉赔偿处理");
        }

        omsOtherissuebill.setExchangerate(BigDecimal.ONE);
        omsOtherissuebill.setAccountcompanynumber(storageorgnumber);
        omsOtherissuebill.setAccountcompanyname(storageorgname);
        omsOtherissuebill.setCurrency("CNY");
        omsOtherissuebill.setSrcbillnumber(omsSalereturnbill.getCode());
        omsOtherissuebill.setSrcbilltype("销售退货");
        omsOtherissuebill.setCreateTime(new Date());
//        omsOtherissuebill.set

        List<OmsSalereturnbillentry> omsSalereturnbillentryList = omsSalereturnbill.getOmsSalereturnbillentryList();
        ArrayList<OmsOtherissuebillentry> omsOtherissuebillentries = new ArrayList<>();
        for (OmsSalereturnbillentry salereturnbillentry : omsSalereturnbillentryList) {
            OmsOtherissuebillentry omsOtherissuebillentry = new OmsOtherissuebillentry();
            String returnwarehousecode1 = salereturnbillentry.getReturnwarehousecode();
            String returnwarehousename = salereturnbillentry.getReturnwarehousename();
            String skucode = salereturnbillentry.getSkucode();
            String skuname = salereturnbillentry.getSkuname();
            String unit = salereturnbillentry.getUnit();
            String baseunit = salereturnbillentry.getBaseunit();
            BigDecimal baseqty = salereturnbillentry.getBaseqty();
            BigDecimal qualityundertakeqty = salereturnbillentry.getQualityundertakeqty();
            Long isgift = salereturnbillentry.getIsgift();

            omsOtherissuebillentry.setWarehousenumber(returnwarehousecode1);
            omsOtherissuebillentry.setWarehousename(returnwarehousename);
            omsOtherissuebillentry.setMaterialname(skuname);
            omsOtherissuebillentry.setMaterialnumber(skucode);
//            omsOtherissuebillentry.setQty(qualityrefuseqty);
            omsOtherissuebillentry.setUnitnumber(unit);
            omsOtherissuebillentry.setBaseunitnumber(baseunit);
            omsOtherissuebillentry.setBaseqty(qualityundertakeqty);
            omsOtherissuebillentry.setQty(qualityundertakeqty);
            omsOtherissuebillentry.setIspresent(isgift);

            omsOtherissuebillentries.add(omsOtherissuebillentry);

        }
        omsOtherissuebill.setOmsOtherissuebillentryList(omsOtherissuebillentries);
        return omsOtherissuebill;
    }

    @Override
    public OmsSalereturnbill rebuildSalereturn(OmsSalereturnbill omsSalereturnbill) {

        OmsSalereturnbill omsSalereturnbillcopy = new OmsSalereturnbill();
        BeanUtils.copyProperties(omsSalereturnbill,omsSalereturnbillcopy);
        List<OmsSalereturnbillentry> omsSalereturnbillentryList = omsSalereturnbillcopy.getOmsSalereturnbillentryList();
        ArrayList<OmsSalereturnbillentry> omsSalereturnbillentries = new ArrayList<>();
        for (OmsSalereturnbillentry omsSalereturnbillentry : omsSalereturnbillentryList) {
            BigDecimal qualityrefuseqty = omsSalereturnbillentry.getQualityrefuseqty();
            BigDecimal warehouserefuseqty = omsSalereturnbillentry.getWarehouserefuseqty();
            BigDecimal qty = omsSalereturnbillentry.getQty();
            BigDecimal totalRefuse = qualityrefuseqty.add(warehouserefuseqty);
            //品控拒绝处理数量+仓库拒绝处理数量=售后数量，移除该元素
            if(qty.compareTo(totalRefuse)!=0){
                omsSalereturnbillentries.add(omsSalereturnbillentry);
            }
        }
        omsSalereturnbillcopy.setOmsSalereturnbillentryList(omsSalereturnbillentries);
        return omsSalereturnbillcopy;
    }


}
